import { unbindRocarsApi, callRocarsBundApi, templateIdList } from "./api";
import Taro from "@tarojs/taro";
// import { useTzRouter } from "@/vhooks/useTzRouter";

export const useButton = (state, userType, useTzRouter) => {
  return () => {
    const { status, id, type, ccrnObjArr } = state.rocarsBundBean;
    const { redirectTo, navigateTo, route, navigateBack } = useTzRouter();
    // 重新编辑
    const editClick = () => {
      navigateTo({
        path: "/pages/subHK/bundle/home/index",
        query: {
          opt: 1,
          bundId: id,
          detailToEdit: 1,
        },
      });
    };

    // 解除捆绑
    const unBindClick = () => {
      Taro.showModal({
        content: "确定解绑该条记录吗?",
        confirmText: "确定",
        cancelText: "取消",
      })
        .then((res) => {
          if (res.cancel) {
            return Promise.reject("cancel");
          } else {
            state.handleBtnDisabled = true;
            Taro.showLoading({
              title: "加载中",
            });
            return unbindRocarsApi(id);
          }
        })
        .then(() => {
          Taro.hideLoading();
          // 发起订阅消息的授权
          Taro.requestSubscribeMessage({
            tmplIds: templateIdList,
            complete(res) {
              console.log(res[templateIdList[0]]);
            },
          });

          return Taro.showModal({
            content:
              "提示:已申报到海关,请等待3~5分钟后,进入【香港捆绑查询】查看状态.",
            confirmText: "好",
            showCancel: false,
          });
        })
        .then(() => {
          redirectTo({
            path: "/pages/subHK/bundleInquire/home/index",
          });
        })
        .catch((err) => {
          Taro.hideLoading();
          state.handleBtnDisabled = false;
          if (err === "cancel") return;
          Taro.showToast({
            title: err.data.msg || "解绑失败",
            icon: "none",
            duration: 3000,
          });
        });
    };

    const checkCcrnFail = () => {
      let errorMsg = "";
      const result = ccrnObjArr.some((item) => {
        const ccrn = item;
        const str = ccrn[0];
        if (type === "I") {
          if ((str !== "1" && str !== "3") || ccrn.length !== 10) {
            errorMsg = "大陆—>香港,CCRN号必须是1或3开头的十位数字！";
            return true;
          }
        } else {
          if ((str !== "2" && str !== "4") || ccrn.length !== 10) {
            errorMsg = "香港—>大陆,CCRN号必须是2或4开头的十位数字！";
            return true;
          }
        }
      });
      if (errorMsg) {
        Taro.showToast({
          title: errorMsg,
          icon: "none",
          duration: 2000,
        });
      }
      return result;
    };

    // 申请捆绑
    const applyBindClick = () => {
      // 验证 ccrn 失败
      if (checkCcrnFail()) return;

      if (
        userType.isPersonal &&
        (state.totalMoney <= 0 || state.totalMoney < state.price)
      ) {
        Taro.showModal({
          content: "账户余额不足,立即充值!",
          confirmText: "确定",
          cancelText: "取消",
        }).then((res) => {
          if (res.cancel) return;
          redirectTo({
            path: "/pages/subUser/recharge/index",
          });
        });
        return;
      }
      state.handleBtnDisabled = true;
      Taro.showLoading({
        title: "加载中",
      });
      callRocarsBundApi(id)
        .then(() => {
          Taro.hideLoading();
          // 发起订阅消息的授权
          Taro.requestSubscribeMessage({
            tmplIds: templateIdList,
            complete(res) {
              // const code = res[templateIdList[0]];
              console.log(res[templateIdList[0]]);
              // $TzNotify.danger("订阅消息状态 " + code);
            },
          });

          return Taro.showModal({
            content:
              "提示:已申报到海关,请等待3~5分钟后,进入【香港捆绑查询】查看状态.",
            confirmText: "好",
            showCancel: false,
          });
        })
        .then((res) => {
          if (res.confirm) {
            route.query?.isNewOrder
              ? redirectTo({
                  path: "/pages/subHK/bundleInquire/home/index",
                })
              : navigateBack({
                  delta: 1,
                  event: {
                    type: "backRefresh",
                  },
                });
          }
          return;
        })
        .catch((err) => {
          $TzNotify.danger(err.data?.msg || "申请捆绑失败");
          state.handleBtnDisabled = false;
        });
    };

    let btnDom;
    if (["DRAFT", "ERROR"].includes(status)) {
      btnDom = (
        <tz-view class="btn-wrap abreast">
          <tz-button
            disabled={state.handleBtnDisabled}
            type="default"
            onClick={editClick}
          >
            重新编辑
          </tz-button>
          <tz-button
            disabled={state.handleBtnDisabled}
            type="danger"
            onClick={applyBindClick}
          >
            申请捆绑
          </tz-button>
        </tz-view>
      );
    } else if (status === "GOVTRECEIVED") {
      btnDom = (
        <tz-button
          disabled={state.handleBtnDisabled}
          type="danger"
          onClick={unBindClick}
        >
          解除捆绑
        </tz-button>
      );
    }

    return (
      <tz-view class="btn-area">
        {btnDom}
        <tz-button
          type="primary"
          onClick={() => {
            route.query?.isNewOrder
              ? redirectTo({
                  path: "/pages/subHK/bundleInquire/home/index",
                })
              : navigateBack({ delta: 1 });
          }}
        >
          返回查询
        </tz-button>
      </tz-view>
    );
  };
};
